import { defineStore } from "pinia";

export interface User {
  id: number;
  username: string;
  email: string;
  phone?: string;
  realName: string;
  avatar?: string;
  department?: string;
  classInfo?: string;
  status: "active" | "inactive" | "suspended";
  createdAt: string;
  updatedAt: string;
  roles: Array<{
    id: number;
    name: string;
  }>;
}

interface UserState {
  currentUser: User | null;
  token: string | null;
  loading: boolean;
}

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    currentUser: null,
    token: null,
    loading: false,
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) =>
      state.currentUser?.roles?.some((role) => role.name === "admin") || false,
    userAvatar: (state) => state.currentUser?.avatar || "",
    userName: (state) =>
      state.currentUser?.realName || state.currentUser?.username || "",
  },

  actions: {
    // 设置用户信息
    setUser(user: User) {
      this.currentUser = user;
    },

    // 设置token
    setToken(token: string) {
      this.token = token;
      // 同时保存到localStorage
      if (process.client) {
        localStorage.setItem("auth_token", token);
      }
    },

    // 登录
    async login(credentials: { username: string; password: string }) {
      this.loading = true;
      try {
        const response = await $fetch("/api/auth/login", {
          method: "POST",
          body: credentials,
        });

        if (response.success) {
          this.setUser(response.data.user);
          this.setToken(response.data.token);
          return { success: true };
        } else {
          return { success: false, message: response.message };
        }
      } catch (error: any) {
        console.error("登录失败:", error);
        return { success: false, message: error.message || "登录失败" };
      } finally {
        this.loading = false;
      }
    },

    // 登出
    logout() {
      this.currentUser = null;
      this.token = null;
      if (process.client) {
        localStorage.removeItem("auth_token");
        localStorage.removeItem("user_info");
      }
      navigateTo("/login");
    },

    // 初始化用户状态（从localStorage恢复）
    initUser() {
      if (process.client) {
        const token = localStorage.getItem("auth_token");
        const userInfo = localStorage.getItem("user_info");

        if (token) {
          this.token = token;
        }

        if (userInfo) {
          try {
            this.currentUser = JSON.parse(userInfo);
          } catch (error) {
            console.error("解析用户信息失败:", error);
          }
        }
      }
    },

    // 更新用户信息
    async updateUser(userData: Partial<User>) {
      if (!this.currentUser) return { success: false, message: "用户未登录" };

      try {
        const response = await $fetch(`/api/users/${this.currentUser.id}`, {
          method: "PUT",
          body: userData,
        });

        if (response.success) {
          this.currentUser = { ...this.currentUser, ...userData };
          return { success: true };
        } else {
          return { success: false, message: response.message };
        }
      } catch (error: any) {
        console.error("更新用户信息失败:", error);
        return { success: false, message: error.message || "更新失败" };
      }
    },
  },
});
